package org.goldfish.mapreduce.orders;

import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.util.StringTokenizer;

@Slf4j
public class OrderMapper extends Mapper
        <LongWritable, Text, OrderKey, IntWritable> {
    private static Order loadOrder(StringTokenizer itr) {
        Order.OrderBuilder builder = Order.builder();
        builder.orderId(itr.nextToken());
        builder.userId(itr.nextToken());
        builder.orderAmount(Integer.parseInt(itr.nextToken()));
        builder.orderTime(itr.nextToken());
        return builder.build();
    }

    @Override
    public void map(LongWritable key, Text value, Context context)
            throws java.io.IOException, InterruptedException {
        String line = value.toString();
        log.info("map: {}", line);
        StringTokenizer itr = new StringTokenizer(line, ",");
        Order order = loadOrder(itr);
        context.write(order.getOrderKey(), new IntWritable(order.getOrderAmount()));
    }
}
